import tkinter as tk
from tkinter import messagebox
  
def center_window(window, width=None, height=None):  
    """  
    Centers the window on the screen.  
  
    Parameters:  
        window (tk.Tk | tk.Toplevel): The window to be centered.  
        width (int, optional): The desired width of the window. Defaults to None.  
        height (int, optional): The desired height of the window. Defaults to None.  
    """  
    screen_width = window.winfo_screenwidth()  
    screen_height = window.winfo_screenheight()  
  
    # If no width/height are given, use the window's dimensions  
    if width is None:  
        width = window.winfo_reqwidth()  
    if height is None:  
        height = window.winfo_reqheight()  
  
    # Calculate position x, y  
    x = (screen_width // 2) - (width // 2)  
    y = (screen_height // 2) - (height // 2)  
    window.geometry(f"{width}x{height}+{int(x)}+{int(y)}")  
  
  
class EmbeddedWindow(tk.Frame):  
    def __init__(self, master, title):  
        super().__init__(master, bd=2, relief="ridge")  
        self.title_label = tk.Label(self, text=title, font=("Helvetica", 12, "bold"))  
        self.title_label.pack(side="top", fill="x", pady=5)  
          
        # 添加一些内容  
        self.content_label = tk.Label(self, text="这是嵌入的子窗口的内容")  
        self.content_label.pack(pady=10)
        self.content_label.bind("<Button-1>", self.on_click)
        #self.button1 = tk.Button(self, text="点击我", command=self.on_click_2)
        self.button1 = tk.Button(self, text="点击我")
        self.button1.bind("<Button-1>", self.on_click_1)
        self.button1.pack(side="left", pady = 5, padx = 10)
    def on_click(self, event):  
        #print("点击了嵌入的子窗口")  
        # 这里可以添加处理点击的代码
        tk.messagebox.showinfo("提示", "点击了嵌入的子窗口", parent=self)
    def on_click_1(self, event):
        messagebox.showinfo("提示", "点击了嵌入的子窗口中的按钮", parent=self)
    def on_click_2(self):
        messagebox.showinfo("提示2", "点击了嵌入的子窗口中的按钮", parent=self)
  
def create_embedded_window():  
    global embedded_window  # 声明为全局变量，以便稍后访问和更新  
    if not hasattr(create_embedded_window, 'frame'):  
        # 如果还没有创建过Frame，则创建一个  
        create_embedded_window.frame = EmbeddedWindow(root, "嵌入的子窗口")  
        create_embedded_window.frame.grid(row=0, column=0, sticky="nsew")  
    else:  
        # 如果已经存在Frame，则将其提到顶层（如果需要）  
        create_embedded_window.frame.tkraise()  
  
# 创建主窗口  
root = tk.Tk()  
root.title("主窗口")
center_window(root, 1024, 768)
  
# 创建菜单栏  
menubar = tk.Menu(root)  
filemenu = tk.Menu(menubar, tearoff=0)  
filemenu.add_command(label="显示嵌入的子窗口", command=create_embedded_window)  
menubar.add_cascade(label="文件", menu=filemenu)  
root.config(menu=menubar)  
  
# 使用grid_rowconfigure和grid_columnconfigure确保主窗口可以调整大小  
root.grid_rowconfigure(0, weight=1)  
root.grid_columnconfigure(0, weight=1)  
  
# 运行主循环  
root.mainloop()
